import React, { useEffect, useRef, useState, useCallback } from "react";
import { useI18n } from "../i18n";
import { siteApi } from "../api/login";
import { SiteInfo } from "../api/types";
import { getLocation } from "zmp-sdk";

// 声明全局的Google Maps类型
declare global {
  interface Window {
    google: any;
    initMap: () => void;
  }
}

interface MapProps {
  className?: string;
  style?: React.CSSProperties;
  center?: { lat: number; lng: number };
  zoom?: number;
  onMerchantClick?: (merchant: SiteInfo) => void;
}

// 防抖函数
const debounce = (func: Function, delay: number) => {
  let timeoutId: number;
  return (...args: any[]) => {
    clearTimeout(timeoutId);
    timeoutId = window.setTimeout(() => func.apply(null, args), delay);
  };
};

// 节流函数
const throttle = (func: Function, delay: number) => {
  let lastCall = 0;
  return (...args: any[]) => {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      func.apply(null, args);
    }
  };
};

const Map: React.FunctionComponent<MapProps> = ({ 
  className, 
  style, 
  center,
  zoom = 13,
  onMerchantClick
}) => {
  const { t } = useI18n();
  const mapRef = useRef<HTMLDivElement>(null);
  const mapInstanceRef = useRef<any>(null);
  const markersRef = useRef<any[]>([]);
  const userLocationMarkerRef = useRef<any>(null);
  const watchIdRef = useRef<number | null>(null);
  
  const [merchants, setMerchants] = useState<SiteInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string>("");
  const [userLocation, setUserLocation] = useState<{ lat: number; lng: number } | null>(null);

  // 默认中心点设置为胡志明市
  const defaultCenter = { lat: 10.8231, lng: 106.6297 };
  const mapCenter = center || userLocation || defaultCenter;

  // 获取附近商家
  const fetchNearbyMerchants = useCallback(async (lat: number, lng: number) => {
    setLoading(true);
    setError("");

    try {
      const params = {
        lng: lng,
        lat: lat,
        distance: 5, // 5公里
        total: 200,  // 200个商户
      };

      const { data } = await siteApi.getAroundSites(params);
      console.log("地图获取附近商家:", data);
      setMerchants(data || []);
      
      // 清除旧标记
      clearMarkers();
      
      // 添加新标记
      if (data && data.length > 0) {
        addMerchantMarkers(data);
      }
    } catch (err: any) {
      console.error("获取附近商家错误:", err);
      setError(err.message || t("merchants.fetchFailed"));
      setMerchants([]);
      clearMarkers();
    } finally {
      setLoading(false);
    }
  }, [t]);

  // 防抖的获取商家函数
  const debouncedFetchMerchants = useCallback(
    debounce(fetchNearbyMerchants, 1000), // 1秒防抖
    [fetchNearbyMerchants]
  );

  // 节流的获取商家函数（用于地图移动）
  const throttledFetchMerchants = useCallback(
    throttle(fetchNearbyMerchants, 2000), // 2秒节流
    [fetchNearbyMerchants]
  );

  // 清除所有标记
  const clearMarkers = useCallback(() => {
    markersRef.current.forEach(marker => {
      if (marker) {
        marker.setMap(null);
      }
    });
    markersRef.current = [];
  }, []);

  // 添加商家标记
  const addMerchantMarkers = useCallback((merchants: SiteInfo[]) => {
    if (!mapInstanceRef.current) return;

    merchants.forEach((merchant) => {
      // 创建自定义图标SVG
      const iconSvg = `
        <svg width="80" height="60" viewBox="0 0 80 60" xmlns="http://www.w3.org/2000/svg">
          <!-- 图标圆形背景 -->
          <circle cx="40" cy="20" r="18" fill="${merchant.open ? '#FF6B35' : '#FF6B6B'}" stroke="white" stroke-width="3"/>
          <!-- 店铺图标 -->
          <text x="40" y="26" text-anchor="middle" fill="white" font-size="16" font-weight="bold">🏪</text>
      <rect x="0" y="35" width="80" height="20" rx="4" fill="rgba(255, 255, 255, 0.95)" stroke="rgba(0,0,0,0.1)" stroke-width="1"/>
          <!-- 商家名称 -->
          <text x="40" y="48" text-anchor="middle" fill="#FF6B35" font-size="12" font-weight="500">${merchant.name.length > 8 ? merchant.name.substring(0, 8) + '...' : merchant.name}</text>
        </svg>
      `;
      // <!-- 名称背景 -->
      //
      // 创建自定义标记
      const marker = new window.google.maps.Marker({
        position: { lat: merchant.lat, lng: merchant.lng },
        map: mapInstanceRef.current,
        title: merchant.name,
        icon: {
          url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(iconSvg),
          scaledSize: new window.google.maps.Size(80, 60),
          anchor: new window.google.maps.Point(40, 20)
        }
      });

      // 添加点击事件
      marker.addListener('click', () => {
        if (onMerchantClick) {
          onMerchantClick(merchant);
        }
      });

      // 添加信息窗口
      const infoWindow = new window.google.maps.InfoWindow({
        content: `
          <div style="padding: 8px; min-width: 200px;">
            <h3 style="margin: 0 0 8px 0; font-size: 14px; color: #333;">${merchant.name}</h3>
            <p style="margin: 0 0 4px 0; font-size: 12px; color: #666;">${merchant.address}</p>
            <p style="margin: 0 0 4px 0; font-size: 12px; color: #666;">营业时间: ${merchant.open_time}</p>
            <p style="margin: 0 0 4px 0; font-size: 12px; color: #666;">
              状态: <span style="color: ${merchant.open ? '#FF6B35' : '#FF6B6B'}">${merchant.open ? '营业中' : '已关闭'}</span>
            </p>
            <p style="margin: 0; font-size: 12px; color: #666;">
              可借: ${merchant.depotBorrow || 0} | 可还: ${merchant.depotEmpty || 0}
            </p>
          </div>
        `
      });

      marker.addListener('click', () => {
        infoWindow.open(mapInstanceRef.current, marker);
      });

      markersRef.current.push(marker);
    });
  }, [onMerchantClick]);

  // 获取用户当前位置 - 使用Zalo SDK
  const getCurrentLocation = useCallback(() => {
    console.log('使用Zalo SDK获取位置...');
    
    getLocation({
      success: (data) => {
        console.log('Zalo SDK位置数据:', data);
        
        if (data && data.latitude && data.longitude) {
          const newLocation = { 
            lat: parseFloat(data.latitude), 
            lng: parseFloat(data.longitude) 
          };
          setUserLocation(newLocation);
          setError(""); // 清除错误信息
          
          // 移动地图到用户位置
          if (mapInstanceRef.current) {
            mapInstanceRef.current.setCenter(newLocation);
            mapInstanceRef.current.setZoom(15);
          }
          
          // 添加用户位置标记
          if (userLocationMarkerRef.current) {
            userLocationMarkerRef.current.setMap(null);
          }
          
          userLocationMarkerRef.current = new window.google.maps.Marker({
            position: newLocation,
            map: mapInstanceRef.current,
            title: t("map.getCurrentLocation"),
            icon: {
              url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(`
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <circle cx="10" cy="10" r="8" fill="#007AFF" stroke="white" stroke-width="2"/>
                  <circle cx="10" cy="10" r="3" fill="white"/>
                </svg>
              `),
              scaledSize: new window.google.maps.Size(20, 20),
              anchor: new window.google.maps.Point(10, 10)
            }
          });

          // 获取附近商家
          debouncedFetchMerchants(parseFloat(data.latitude), parseFloat(data.longitude));
        } else {
          console.warn('Zalo SDK返回的位置数据格式不正确:', data);
          console.log('使用默认位置作为备用方案');
          setUserLocation(defaultCenter);
          setError(""); // 清除错误，使用默认位置
          
          // 移动地图到默认位置
          if (mapInstanceRef.current) {
            mapInstanceRef.current.setCenter(defaultCenter);
            mapInstanceRef.current.setZoom(13);
          }
          
          // 获取默认位置附近的商家
          debouncedFetchMerchants(defaultCenter.lat, defaultCenter.lng);
        }
      },
      fail: (error) => {
        console.error("Zalo SDK获取位置失败:", error);
        console.log('使用默认位置作为备用方案');
        
        // 使用默认位置作为备用方案
        setUserLocation(defaultCenter);
        setError(""); // 清除错误，使用默认位置
        
        // 移动地图到默认位置
        if (mapInstanceRef.current) {
          mapInstanceRef.current.setCenter(defaultCenter);
          mapInstanceRef.current.setZoom(13);
        }
        
        // 获取默认位置附近的商家
        debouncedFetchMerchants(defaultCenter.lat, defaultCenter.lng);
        
        // 根据错误类型显示不同的错误信息（但不阻止使用默认位置）
        if (error.code === 1 || error.message?.includes('permission') || error.message?.includes('denied')) {
          console.warn('位置权限被拒绝，使用默认位置');
        } else if (error.code === 2 || error.message?.includes('unavailable')) {
          console.warn('位置服务不可用，使用默认位置');
        } else if (error.code === 3 || error.message?.includes('timeout')) {
          console.warn('获取位置超时，使用默认位置');
        } else {
          console.warn('获取位置失败，使用默认位置');
        }
      }
    });
  }, [t, debouncedFetchMerchants]);

  // 监听位置变化 - 使用定时器定期获取位置
  const watchLocation = useCallback(() => {
    // 每30秒获取一次位置
    const intervalId = setInterval(() => {
      getLocation({
        success: (data) => {
          if (data && data.latitude && data.longitude) {
            const newLocation = { 
              lat: parseFloat(data.latitude), 
              lng: parseFloat(data.longitude) 
            };
            
            // 检查位置是否显著变化（超过100米）
            if (userLocation) {
              const distance = window.google?.maps?.geometry?.spherical?.computeDistanceBetween(
                new window.google.maps.LatLng(userLocation.lat, userLocation.lng),
                new window.google.maps.LatLng(parseFloat(data.latitude), parseFloat(data.longitude))
              );
              
              if (distance && distance < 100) {
                return; // 位置变化不大，不重新查询
              }
            }
            
            setUserLocation(newLocation);
            
            // 更新用户位置标记
            if (userLocationMarkerRef.current) {
              userLocationMarkerRef.current.setPosition(newLocation);
            }
            
            // 节流查询附近商家
            throttledFetchMerchants(parseFloat(data.latitude), parseFloat(data.longitude));
          }
        },
        fail: (error) => {
          console.error("监听位置失败:", error);
          // 不显示错误，因为这是后台监听
        }
      });
    }, 30000); // 30秒间隔
    
    // 返回清理函数
    return () => {
      clearInterval(intervalId);
    };
  }, [userLocation, throttledFetchMerchants]);

  useEffect(() => {
    // 检查Google Maps API是否已加载
    if (typeof window.google === 'undefined') {
      console.warn('Google Maps API 尚未加载');
      return;
    }

    // 初始化地图
    const initMap = () => {
      if (mapRef.current && !mapInstanceRef.current) {
        console.log('初始化地图，中心点:', mapCenter);
        mapInstanceRef.current = new window.google.maps.Map(mapRef.current, {
          center: mapCenter,
          zoom: zoom,
          mapTypeId: 'roadmap',
          disableDefaultUI: false, // 启用一些UI控件
          zoomControl: false, // 禁用放大缩小按钮
          mapTypeControl: false,
          scaleControl: true,
          streetViewControl: false,
          rotateControl: false,
          fullscreenControl: false // 禁用全屏按钮
        });

        // 添加地图移动监听
        mapInstanceRef.current.addListener('dragend', () => {
          const center = mapInstanceRef.current.getCenter();
          if (center) {
            throttledFetchMerchants(center.lat(), center.lng());
          }
        });

        // 添加缩放监听
        mapInstanceRef.current.addListener('zoom_changed', () => {
          const center = mapInstanceRef.current.getCenter();
          if (center) {
            throttledFetchMerchants(center.lat(), center.lng());
          }
        });

        // 如果提供了center，获取附近商家
        if (center) {
          debouncedFetchMerchants(center.lat, center.lng);
        }
      }
    };

    // 如果Google Maps API已经加载，直接初始化
    if (window.google && window.google.maps) {
      initMap();
    } else {
      // 否则等待API加载完成
      window.initMap = initMap;
    }

    // 清理函数
    return () => {
      if (typeof window.initMap === 'function') {
        (window as any).initMap = undefined;
      }
      clearMarkers();
      if (userLocationMarkerRef.current) {
        userLocationMarkerRef.current.setMap(null);
      }
    };
  }, [mapCenter, zoom, center, debouncedFetchMerchants, throttledFetchMerchants, clearMarkers]);

  // 组件挂载时获取位置
  useEffect(() => {
    getCurrentLocation();
    const cleanupWatch = watchLocation();
    
    return () => {
      if (cleanupWatch) {
        cleanupWatch();
      }
    };
  }, [getCurrentLocation, watchLocation]);

  return (
    <div 
      className={className}
      style={{
        width: '100%',
        height: '100%',
        position: 'relative',
        ...style
      }}
    >
      {/* 加载状态 */}
      {loading && (
        <div
          style={{
            position: 'absolute',
            top: '10px',
            left: '50%',
            transform: 'translateX(-50%)',
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            padding: '8px 16px',
            borderRadius: '20px',
            fontSize: '12px',
            color: '#666',
            zIndex: 1000,
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}
        >
          {t("map.loadingMerchants")}
        </div>
      )}

      {/* 错误提示 */}
      {error && (
        <div
          style={{
            position: 'absolute',
            top: '10px',
            left: '50%',
            transform: 'translateX(-50%)',
            backgroundColor: '#ffebee',
            padding: '8px 16px',
            borderRadius: '20px',
            fontSize: '12px',
            color: '#c62828',
            zIndex: 1000,
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
            maxWidth: '80%',
            textAlign: 'center'
          }}
        >
          {error}
          {error.includes('权限') && (
            <div style={{ marginTop: '4px', fontSize: '10px', color: '#666' }}>
              请在Zalo设置中允许位置权限
            </div>
          )}
        </div>
      )}

      {/* 无商家提示 */}
      {!loading && merchants.length === 0 && !error && (
        <div
          style={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            padding: '16px 24px',
            borderRadius: '12px',
            fontSize: '14px',
            color: '#666',
            zIndex: 1000,
            boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
            textAlign: 'center'
          }}
        >
          {t("map.noMerchantsNearby")}
        </div>
      )}

      {/* 定位按钮 */}
      <button
        onClick={getCurrentLocation}
        style={{
          position: 'absolute',
          bottom: '20px',
          right: '20px',
          width: '44px',
          height: '44px',
          backgroundColor: 'white',
          border: 'none',
          borderRadius: '22px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
          cursor: 'pointer',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: '18px',
          zIndex: 1000
        }}
        title={t("map.getCurrentLocation")}
      >
        📍
      </button>

      {/* 谷歌地图容器 */}
      <div 
        ref={mapRef}
        style={{
          width: '100%',
          height: '100%'
        }}
      />
    </div>
  );
};

export default Map;
